<?php namespace App\Http\Controllers\Api\Admin;

use App\DakaContent;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;

class DakaController extends Controller
{
    public function setDakaContent(Request $request){
        if(Auth::guard('admin')->guest()){
            return response()->json(["level"=>"error","message"=>"不允许访问"]);
        }

        $did      = !is_null($request->get('d_id')) ? $request->get('d_id') : 0;
        $title    = $request->get("title");
        $desc     = $request->get("desc");
        $content  = $request->get("content");
        $isActive = $request->get("is_active");
        $imgId    = $request->get("img_id");

        /** @var DakaContent $thatDaka */
        $thatDaka = DakaContent::whereId($did)->first();

        if(!$thatDaka){
            $thatDaka = new DakaContent();
        }

        if(!is_null($title))$thatDaka->title = $title;
        if(!is_null($desc))$thatDaka->desc = $desc;
        if(!is_null($content))$thatDaka->content = $content;
        if(!is_null($imgId))$thatDaka->img_id = $imgId;

        if(!is_null($isActive) && (int)$isActive == 1){
            $oldActiveDaka = DakaContent::whereIsActive(1)->first();
            if($oldActiveDaka){
                $oldActiveDaka->is_active = 0;
                $oldActiveDaka->save();
            }

            $thatDaka->is_active = 1;
        }

        $thatDaka->save();

        return response()->json(["level"=>"success","message"=>"设置完成","data"=>$thatDaka]);


    }

    public function delDaka(Request $request){
        $did = $request->get("d_id");

        /** @var DakaContent $thatDaka */
        $thatDaka = DakaContent::whereId($did)->first();

        if(!$thatDaka)
            return response()->json(["level"=>"error","message"=>"当前打卡任务不存在"]);

        $thatDaka->delete();

        return response()->json(["level"=>"success","message"=>"删除成功"]);
    }
}